/**
 * 静态方法
 * Name = resourceUtil
 * DateTime = Mon Jan 17 2022 13:42:44 GMT+0800 (中国标准时间)
 * Author = Created by zhj9922
 * FileBasename = resourceUtil.ts
 * gitee： https://gitee.com/coyeking
 */
 
 import { _decorator, Prefab, Node, SpriteComponent, SpriteFrame, Rect, ImageAsset, resources, error, Texture2D, instantiate, isValid, find, loader, Color, assetManager } from "cc";
 const { ccclass } = _decorator;
 
 @ccclass("resourceUtil")
 export class resourceUtil {
     /**
      * 加载资源
      * @param url   资源路径
      * @param type  资源类型
      * @param cb    回调
      * @method loadRes
      */
     public static loadRes(url: string, type: any, cb: Function) {
         resources.load(url, (err: any, res: any) => {
             if (err) {
                 error(err.message || err);
                 cb(err, res);
                 return;
             }
 
             cb(null, res);
         })
     }
 
     public static loadSpriteFrameResPromise(path: string) {
         return new Promise((resolve, reject) => {
             this.loadRes(path, SpriteFrame, (err: any, img: ImageAsset) => {
                 if (err) {
                     console.error('spriteFrame load failed!', path, err);
                     reject && reject();
                     return;
                 }
 
                 let texture = new Texture2D();
                 texture.image = img;
 
                 let sf = new SpriteFrame();
                 sf.texture = texture;
 
                 resolve && resolve(sf);
             })
         })
     }
 
     public static loadSpriteFrameRes(path: string, sprite: SpriteComponent, cb?: Function) {
         this.loadSpriteFrameResPromise(path).then((sf) => {
             if (sprite && isValid(sprite)) {
                 sprite.spriteFrame = sf as SpriteFrame;
                 cb && cb();
             } else {
                 console.log("sprite is null");
             }
         })
     }

     
     /**
      * 加载远程图片资源
      * @param imgUrl 
      * @param target_ 
      * @param callBack 
      */
    public static loadRemoteImg (imgUrl: string,target_:SpriteComponent,callBack?: (response?: any) => void) {
        assetManager.loadRemote(imgUrl,{ ext: '.png' },function (error, imgast:ImageAsset) {
            if (error) {
                console.log(error);
                return;
            }
            let texture = new Texture2D();
            texture.image = imgast;
            const spFrame = new SpriteFrame();
            spFrame.texture = texture;

            target_.spriteFrame = spFrame;
            callBack&&callBack()
        });
    };
    
 }
 

